<template>
  <div class="order-container">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="开单申请"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />

    <!-- 开单申请内容 -->
    <div class="order-content">
      <!-- 院区信息显示 -->
      <div class="hospital-info">
        <div class="info-header">
          <van-icon name="location-o" size="16" color="#1989fa" />
          <span>当前选择院区</span>
        </div>
        <div class="hospital-name">{{ selectedHospital.name }}</div>
        <div class="hospital-address">{{ selectedHospital.address }}</div>
      </div>

      <!-- 检查项目分类 -->
      <div class="category-tabs">
        <van-tabs v-model:active="activeCategory" @change="onCategoryChange">
          <van-tab title="检验项目" name="lab">
            <div class="project-list">
              <!-- 加载状态 -->
              <div v-if="projectsLoading" class="loading-container">
                <van-loading size="24px" vertical>加载检查项目中...</van-loading>
              </div>
              
              <!-- 项目列表 -->
              <div v-else>
                <div 
                  v-for="item in labProjects" 
                  :key="item.id"
                  class="project-item"
                  @click="toggleProject(item)"
                >
                  <div class="project-info">
                    <div class="project-name">{{ item.name }}</div>
                    <div class="project-desc">{{ item.description }}</div>
                    <div class="project-price">¥ {{ item.price }}</div>
                  </div>
                  <div class="project-checkbox">
                    <van-checkbox 
                      v-model="item.selected" 
                      @click.stop="toggleProject(item)"
                    />
                  </div>
                </div>
              </div>
            </div>
          </van-tab>
          
          <van-tab title="检查项目" name="exam">
            <div class="project-list">
              <!-- 加载状态 -->
              <div v-if="projectsLoading" class="loading-container">
                <van-loading size="24px" vertical>加载检查项目中...</van-loading>
              </div>
              
              <!-- 项目列表 -->
              <div v-else>
                <div 
                  v-for="item in examProjects" 
                  :key="item.id"
                  class="project-item"
                  @click="toggleProject(item)"
                >
                  <div class="project-info">
                    <div class="project-name">{{ item.name }}</div>
                    <div class="project-desc">{{ item.description }}</div>
                    <div class="project-price">¥ {{ item.price }}</div>
                  </div>
                  <div class="project-checkbox">
                    <van-checkbox 
                      v-model="item.selected" 
                      @click.stop="toggleProject(item)"
                    />
                  </div>
                </div>
              </div>
            </div>
          </van-tab>
        </van-tabs>
      </div>

      <!-- 已选项目汇总 -->
      <div class="selected-summary" v-if="selectedProjects.length > 0">
        <div class="summary-header">
          <span>已选项目 ({{ selectedProjects.length }}项)</span>
          <van-button 
            type="primary" 
            size="mini" 
            @click="clearAll"
          >
            清空
          </van-button>
        </div>
        <div class="selected-list">
          <div 
            v-for="item in selectedProjects" 
            :key="item.id"
            class="selected-item"
          >
            <span class="item-name">{{ item.name }}</span>
            <span class="item-price">¥{{ item.price }}</span>
            <van-icon 
              name="cross" 
              size="14" 
              @click="removeProject(item)"
              class="remove-btn"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 底部提交区域 -->
    <div class="bottom-submit">
      <div class="total-info">
        <div class="total-count">共{{ selectedProjects.length }}项</div>
        <div class="total-price">合计：¥{{ totalPrice }}</div>
      </div>
      <van-button 
        type="primary" 
        size="large" 
        :disabled="selectedProjects.length === 0"
        @click="submitOrder"
        class="submit-btn"
      >
        提交申请
      </van-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Toast, Dialog } from 'vant'
import { apiService, type SubmitOrderApplicationRequest, type OrderApplicationItem, type ExaminationProject } from '@/api'
import { useUserStore } from '@/stores/user'

/**
 * 开单申请页面组件
 * 用户可以选择检验和检查项目，提交开单申请
 */

const router = useRouter()
const userStore = useUserStore()
const route = useRoute()
const activeCategory = ref('lab')



/**
 * 项目数据接口
 */
interface Project {
  id: number
  name: string
  description?: string
  price: number
  selected: boolean
  category: number // 0: 检验项目, 1: 检查项目
}

/**
 * 医院信息接口
 */
interface Hospital {
  id: number
  name: string
  address: string
}

/**
 * 当前选择的医院信息（从路由参数获取）
 */
const selectedHospital = ref<Hospital>({
  id: 1,
  name: '智慧医疗总院本部',
  address: '市中心区健康大道123号'
})

/**
 * 获取检查项目数据
 */
const fetchExaminationProjects = async () => {
  try {
    projectsLoading.value = true
    
    // 获取指定院区的所有医疗项目
    const response = await apiService.getExaminationProjects(selectedHospital.value.id)
    
    if (response.code === 200 && response.data) {
      // 将项目按分类分组
      const projects = response.data.map(project => ({
        ...project,
        selected: false
      }))
      
      // 分离检验项目和检查项目（后端使用数字：0-检验项目，1-检查项目）
      labProjects.value = projects.filter(p => p.category === 0)
      examProjects.value = projects.filter(p => p.category === 1)
    } else {
      // 如果API调用失败，使用默认数据
      console.warn('获取检查项目失败，使用默认数据')
      loadDefaultProjects()
    }
  } catch (error) {
    console.error('获取检查项目失败:', error)
    // 如果网络错误，使用默认数据
    loadDefaultProjects()
  } finally {
    projectsLoading.value = false
  }
}

/**
 * 加载默认项目数据（备用方案）
 */
const loadDefaultProjects = () => {
  labProjects.value = [
    { id: 1, name: '血常规', category: 0, price: 25, description: '检查血液中各种细胞的数量和形态', code: 'LAB001', estimatedDuration: 30, preparationInstructions: '空腹8-12小时', sortOrder: 1, selected: false },
    { id: 2, name: '尿常规', category: 0, price: 15, description: '检查尿液的物理和化学性质', code: 'LAB002', estimatedDuration: 15, preparationInstructions: '留取中段尿', sortOrder: 2, selected: false },
    { id: 3, name: '肝功能', category: 0, price: 80, description: '检查肝脏功能指标', code: 'LAB003', estimatedDuration: 45, preparationInstructions: '空腹8-12小时', sortOrder: 3, selected: false },
    { id: 4, name: '肾功能', category: 0, price: 60, description: '检查肾脏功能指标', code: 'LAB004', estimatedDuration: 45, preparationInstructions: '空腹8-12小时', sortOrder: 4, selected: false },
    { id: 5, name: '血糖', category: 0, price: 10, description: '检查血液中葡萄糖含量', code: 'LAB005', estimatedDuration: 15, preparationInstructions: '空腹8-12小时', sortOrder: 5, selected: false },
    { id: 6, name: '血脂', category: 0, price: 45, description: '检查血液中脂类含量', code: 'LAB006', estimatedDuration: 30, preparationInstructions: '空腹8-12小时', sortOrder: 6, selected: false }
  ]
  
  examProjects.value = [
    { id: 7, name: '胸部CT', category: 1, price: 280, description: '胸部计算机断层扫描', code: 'RAD001', estimatedDuration: 20, preparationInstructions: '无特殊要求', sortOrder: 11, selected: false },
    { id: 8, name: '腹部B超', category: 1, price: 120, description: '腹部超声检查', code: 'US001', estimatedDuration: 15, preparationInstructions: '空腹6小时', sortOrder: 12, selected: false },
    { id: 9, name: '心电图', category: 1, price: 30, description: '心脏电活动检查', code: 'ECG001', estimatedDuration: 10, preparationInstructions: '无特殊要求', sortOrder: 13, selected: false },
    { id: 10, name: '头部MRI', category: 1, price: 450, description: '头部磁共振成像', code: 'MRI001', estimatedDuration: 45, preparationInstructions: '取下金属物品', sortOrder: 14, selected: false },
    { id: 11, name: '骨密度检查', category: 1, price: 180, description: '骨骼密度测量', code: 'DEXA001', estimatedDuration: 30, preparationInstructions: '无特殊要求', sortOrder: 15, selected: false },
    { id: 12, name: '胃镜检查', category: 1, price: 350, description: '胃部内镜检查', code: 'ENDO001', estimatedDuration: 30, preparationInstructions: '空腹12小时', sortOrder: 16, selected: false }
  ]
}

/**
 * 页面挂载时获取医院信息
 */
onMounted(async () => {
  userStore.initUserInfo()
  
  // 从路由查询参数中获取医院信息
  const { hospitalId, hospitalName, hospitalAddress } = route.query
  
  if (hospitalId && hospitalName && hospitalAddress) {
    selectedHospital.value = {
      id: parseInt(hospitalId as string),
      name: hospitalName as string,
      address: hospitalAddress as string
    }
    
    // 获取检查项目数据
    await fetchExaminationProjects()
  } else {
    // 如果没有医院信息，返回医院选择页面
    Toast('请先选择医院')
    router.push('/hospital-selection')
  }
})

/**
 * 检验项目列表
 */
const labProjects = ref<(ExaminationProject & { selected: boolean })[]>([])

/**
 * 检查项目列表
 */
const examProjects = ref<(ExaminationProject & { selected: boolean })[]>([])

/**
 * 项目数据加载状态
 */
const projectsLoading = ref(false)

/**
 * 计算已选择的项目
 */
const selectedProjects = computed(() => {
  return [...labProjects.value, ...examProjects.value].filter(item => item.selected)
})

/**
 * 计算总价格
 */
const totalPrice = computed(() => {
  return selectedProjects.value.reduce((total, item) => total + item.price, 0).toFixed(2)
})

/**
 * 点击返回按钮
 */
const onClickLeft = () => {
  if (selectedProjects.value.length > 0) {
    Dialog.confirm({
      title: '确认返回',
      message: '您已选择了项目，返回将清空选择，确认返回吗？'
    }).then(() => {
      router.back()
    }).catch(() => {
      // 用户取消
    })
  } else {
    router.back()
  }
}

/**
 * 切换分类标签
 * @param name 分类名称
 */
const onCategoryChange = (name: string) => {
  console.log('切换到分类:', name)
}

/**
 * 切换项目选择状态
 * @param project 项目信息
 */
const toggleProject = (project: Project) => {
  project.selected = !project.selected
  
  if (project.selected) {
    Toast({
      message: `已添加 ${project.name}`,
      position: 'middle',
      duration: 1000
    })
  }
}

/**
 * 移除已选项目
 * @param project 要移除的项目
 */
const removeProject = (project: Project) => {
  project.selected = false
  Toast({
    message: `已移除 ${project.name}`,
    position: 'middle',
    duration: 1000
  })
}

/**
 * 清空所有选择
 */
const clearAll = () => {
  Dialog.confirm({
    title: '确认清空',
    message: '确认清空所有已选项目吗？'
  }).then(() => {
    labProjects.value.forEach(item => item.selected = false)
    examProjects.value.forEach(item => item.selected = false)
    Toast({
      message: '已清空所有选择',
      position: 'middle'
    })
  }).catch(() => {
    // 用户取消
  })
}

/**
 * 跳转到支付页面
 */
const goToPayment = () => {
  // 将选中的项目信息传递给支付页面
  const orderData = {
    items: selectedProjects.value.map(item => ({
      id: item.id,
      name: item.name,
      description: item.description,
      price: item.price
    })),
    hospital: selectedHospital.value,
    totalAmount: totalPrice.value
  }
  
  // 跳转到支付页面，携带订单数据
  router.push({
    path: '/order-payment',
    query: {
      orderData: JSON.stringify(orderData)
    }
  })
}

/**
 * 跳转到确认页面
 */
const goToConfirmation = () => {
  // 构造确认页面需要的订单数据
  const orderData = {
    items: selectedProjects.value.map(item => ({
      id: item.id,
      name: item.name,
      description: item.description,
      price: item.price,
      category: item.category
    })),
    hospital: selectedHospital.value,
    applicant: '王小明', // 这里应该从用户信息获取
    totalAmount: totalPrice.value
  }
  
  // 跳转到确认页面，携带订单数据和医院信息
  router.push({
    path: '/order-confirmation',
    query: {
      orderData: JSON.stringify(orderData),
      // 额外传递医院信息，确保确认页面能正确显示用户选择的医院
      hospitalName: selectedHospital.value.name,
      hospitalAddress: selectedHospital.value.address
    }
  })
}

/**
 * 提交开单申请
 */
const submitOrder = async () => {
  if (selectedProjects.value.length === 0) {
    Toast('请至少选择一个检查项目')
    return
  }

  Dialog.confirm({
    title: '提交申请',
    message: `确认提交开单申请吗？\n共${selectedProjects.value.length}项，合计¥${totalPrice.value}\n\n提交后将进入确认页面`,
    confirmButtonText: '提交申请',
    cancelButtonText: '取消'
  }).then(async () => {
    try {
      Toast.loading({
        message: '正在提交申请...',
        forbidClick: true,
        duration: 0
      })
      
      // 检查用户是否已登录
      if (!userStore.isLoggedIn) {
        Toast('请先登录后再提交申请')
        router.push('/login')
        return
      }

      // 构造提交数据
      const orderData: SubmitOrderApplicationRequest = {
        userId: userStore.userId,
        hospitalAreaId: parseInt(selectedHospital.value.id.toString()),
        contactPhone: userStore.userInfo?.phone || '13800138000',
        items: selectedProjects.value.map(project => ({
          medicalProjectId: project.id,  // 医疗项目ID
          quantity: 1                     // 项目数量，默认为1
        })),
        remarks: '前端提交的开单申请'
      }
      
      // 调用API提交申请
      const response = await apiService.submitOrderApplication(orderData)
      
      Toast.clear()
      
      if (response.code === 200) {
        Toast.success({
          message: '申请提交成功！',
          duration: 800
        })
        
        // 跳转到确认页面
        setTimeout(() => {
          goToConfirmation()
        }, 800)
      } else {
        Toast.fail(response.message || '提交失败，请重试')
      }
    } catch (error) {
      Toast.clear()
      console.error('提交开单申请失败:', error)
      Toast.fail('网络错误，请稍后重试')
    }
  }).catch(() => {
    // 用户取消
  })
}
</script>

<style scoped>
.order-container {
  height: 100%;
  max-height: 100vh;
  background-color: #f7f8fa;
  display: flex;
  flex-direction: column;
  max-width: 100%;
  box-sizing: border-box;
  overflow: hidden;
  position: relative;
}

.order-content {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 120px; /* 为底部提交区域留出空间 */
}

/* 院区信息样式 */
.hospital-info {
  background: #fff;
  margin: 12px;
  padding: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.info-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.info-header span {
  margin-left: 6px;
  font-size: 14px;
  color: #666;
}

.hospital-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.hospital-address {
  font-size: 13px;
  color: #999;
}

/* 分类标签样式 */
.category-tabs {
  background: #fff;
  margin: 0 12px 12px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

:deep(.van-tabs__nav) {
  background: #f8f9fa;
}

:deep(.van-tab) {
  font-weight: 500;
}

:deep(.van-tabs__content) {
  padding: 0;
}

/* 项目列表样式 */
.project-list {
  padding: 16px;
}

.project-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  margin-bottom: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 2px solid transparent;
  transition: all 0.3s ease;
  cursor: pointer;
}

.project-item:hover {
  background: #e8f4fd;
  border-color: #1989fa;
}

.project-item:last-child {
  margin-bottom: 0;
}

.project-info {
  flex: 1;
}

.project-name {
  font-size: 15px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.project-desc {
  font-size: 12px;
  color: #666;
  line-height: 1.4;
  margin-bottom: 6px;
}

.project-price {
  font-size: 16px;
  font-weight: bold;
  color: #ff6b35;
}

.project-checkbox {
  margin-left: 12px;
}

/* 已选项目汇总样式 */
.selected-summary {
  background: #fff;
  margin: 0 12px 12px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}



.summary-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: #f0f9ff;
  border-bottom: 1px solid #e1f5fe;
}

.summary-header span {
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.selected-list {
  padding: 12px 16px;
}

.selected-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.selected-item:last-child {
  border-bottom: none;
}

.item-name {
  font-size: 14px;
  color: #333;
  flex: 1;
}

.item-price {
  font-size: 14px;
  font-weight: 600;
  color: #ff6b35;
  margin-right: 12px;
}

.remove-btn {
  color: #999;
  cursor: pointer;
  padding: 4px;
}

.remove-btn:hover {
  color: #ff6b35;
}

/* 底部提交区域样式 */
.bottom-submit {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 16px;
  border-top: 1px solid #ebedf0;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.08);
  z-index: 100;
  max-width: 100%;
  box-sizing: border-box;
}

.total-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.total-count {
  font-size: 14px;
  color: #666;
}

.total-price {
  font-size: 18px;
  font-weight: bold;
  color: #ff6b35;
}

.submit-btn {
  width: 100%;
  height: 44px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 8px;
  max-width: 100%;
  box-sizing: border-box;
}

:deep(.submit-btn .van-button__text) {
  max-width: 100%;
  box-sizing: border-box;
  word-wrap: break-word;
}

/* 顶部导航栏样式 */
:deep(.van-nav-bar) {
  position: sticky;
  top: 0;
  z-index: 100;
  background: #fff;
  border-bottom: 1px solid #ebedf0;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px 20px;
  color: #666;
}

/* 响应式设计 */
@media (max-width: 375px) {
  .hospital-info,
  .category-tabs,
  .selected-summary {
    margin: 0 8px 8px;
  }
  
  .project-list {
    padding: 12px;
  }
  
  .project-item {
    padding: 12px;
    margin-bottom: 8px;
  }
  
  .project-name {
    font-size: 14px;
  }
  
  .project-desc {
    font-size: 11px;
  }
  
  .project-price {
    font-size: 15px;
  }
  
  .bottom-submit {
    padding: 12px;
  }
  
  .submit-btn {
    height: 40px;
    font-size: 15px;
  }
}
</style>